package com.api.gbhg.lbj.action;

import com.api.gbhg.lbj.dao.ReimbursementDao;
import com.api.gbhg.lbj.util.Budgetsources;
import com.api.gbhg.luoao.utils.PageEntity;
import com.api.gbhg.zengping.common.CommonDao;
import com.api.gbhg.zengping.dao.PropertyManagementCostDao;
import com.api.gbhg.zengping.web.PropertyManagementAction;
import com.sap.db.util.StringUtil;
import com.weaver.general.BaseBean;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.workflow.WorkflowVersion;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.api.gbhg.lbj.tool.Tools.getsfkzsydwbxed;

/**
 * @author lbj
 * @version 1.0
 * @description: TODO 明细冻结金额
 * @date 2021/3/9 16:36
 */
public class FrozenamountAction implements Action {
    private static final Logger logger = LoggerFactory.getLogger("gbhg");
    @Override
    public String execute(RequestInfo requestInfo) {

        logger.info("进入明细冻结金额FrozenamountAction---");
        //请求id
        String requestid = requestInfo.getRequestid();
        //标题
        String description = requestInfo.getDescription();
        //获取表名
        String billTableName = requestInfo.getRequestManager().getBillTableName();
        int billid = requestInfo.getRequestManager().getBillid();
        //得到明细表名
        DetailTable[] detailTables = CommonDao.getDetailTables(requestInfo);
        //流程id
        String workflowid = requestInfo.getWorkflowid();
        RecordSet rs = CommonDao.selectByRequestId(new RecordSet(), billTableName, requestid);
        rs.next();
        String mainid = rs.getString("id");

        RecordSet recordSet = CommonDao.selectByDetailTable(detailTables[0].getTableDBName(), mainid);
        Map<String,String>[] list=new HashMap[recordSet.getArray().size()];

        int i=0;
        String ysxm="";
        while (recordSet.next()){
            logger.info("报销冻结执行第 "+i+"行");
            list[i]=new HashMap<>();
            ysxm = recordSet.getString("ysxm");
            String sqbxje = recordSet.getString("sqbxje");
            String bmjjzcfl = recordSet.getString("bmjjzcfl");
            String cxje = recordSet.getString("cxje");
            String tybxje = recordSet.getString("tybxje");
            if (StringUtils.isBlank(cxje)){
                cxje="0.00";
            }
            if (StringUtils.isBlank(tybxje)){
                tybxje="0.00";
            }
            String bxr = recordSet.getString("bxr");
            logger.info("预算项目:"+ysxm+"申请报销金额:"+sqbxje+"部门经济支出分类:"+bmjjzcfl+"mainid:"+mainid);
            list[i].put("workflowid",workflowid);//workflowid
            list[i].put("requestid",requestid);//报销流程id
            list[i].put("lcjlid",ysxm);//预算项目
            list[i].put("money",sqbxje);//申请报销金额
            list[i].put("bmjjzcfl",bmjjzcfl);//部门经济支出分类
            list[i].put("cxje",cxje);//冲销金额
            list[i].put("bxr",bxr);//报销人
            list[i].put("tybxje",tybxje);//报销人
            i++;
        }

        String existsFreeze = existsFreeze(detailTables[0].getTableDBName(),billid);
        if(!existsFreeze.isEmpty()){
            requestInfo.getRequestManager().setMessagecontent(existsFreeze);
            requestInfo.getRequestManager().setMessageid("1");
            return FAILURE_AND_CONTINUE;
        }

        boolean b = true;
        boolean b2 = true;
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        try {

            PropertyManagementAction.addDetail(list,description,workflowid);
            ReimbursementDao rei=new ReimbursementDao();
            b = rei.queryJingfei(rst,list,false,0);
            RecordSet rs1 = getsfkzsydwbxed(ysxm);
            rs1.next();
            String sfkzsydwbxed = rs1.getString("sfkzsydwbxed");
            String lcid = rs1.getString("lcid");
            BaseBean baseBean=new BaseBean();
            String BZ18Workflowid = WorkflowVersion.getActiveVersionWFID(baseBean.getPropValue("FormationWorkflowid", "BZ18Workflowid"));//读取配置文件
            logger.info("是否控制使用单位报销额度:"+sfkzsydwbxed+",workflowid:"+lcid+",BZ18Workflowid:"+BZ18Workflowid);
            if (StringUtils.isNotBlank(sfkzsydwbxed)&&sfkzsydwbxed.equals("1")&&!lcid.equals(BZ18Workflowid)){
                b2 = rei.userQuotaFreezeDeduction(rst,list, true);
            }
            logger.info("b:"+b+",b2:"+b2+",是否控制使用单位报销额度:"+sfkzsydwbxed);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(!b||!b2){
            rst.rollback();
            //删除报销记录
            rs.execute("DELETE FROM uf_bxsjjl WHERE lcid="+requestid);
            rs.execute("DELETE FROM uf_bxjl_kj WHERE lcid="+requestid);
            rs.execute("DELETE FROM uf_bxjl_kj_dt1 WHERE lcid="+requestid);
            rs.execute("DELETE FROM uf_bxjl_kj_dt2 WHERE lcid="+requestid);
            logger.info("=====================冻结错误=======================");
            requestInfo.getRequestManager().setMessagecontent("冻结失败");
            requestInfo.getRequestManager().setMessageid("1");
            return FAILURE_AND_CONTINUE;
        }
        rst.commit();
        return Action.SUCCESS;
    }

    //报销提交时action检查经济分类余额
    public String existsFreeze(String detailtable,int mainid){
        RecordSet rs = new RecordSet();
        RecordSet rs2 = new RecordSet();
        rs.execute("  SELECT ysxm,bmjjzcfl,(SUM(sqbxje)-SUM(ISNULL(cxje,0))) AS sqbxje FROM "+detailtable+" WHERE mainid="+mainid+" GROUP BY ysxm,bmjjzcfl  ");
        while (rs.next()){
            String ysxm = rs.getString("ysxm");
            String bmjjzcfl = rs.getString("bmjjzcfl");
            String sqbxje = rs.getString("sqbxje");
            rs2.execute(" SELECT xmmc,syed ,syed-("+sqbxje+") AS chae FROM uf_jingfei WHERE lcjlid="+ysxm+" AND bmzcjjfl="+bmjjzcfl);
            rs.next();
            Double chae = rs2.getDouble("chae");
            if(chae<0){
                return  "报销预算项目:"+rs2.getString("xmmc")+"的经济分类["+bmjjzcfl+"]剩余额度:"+rs2.getString("syed")+" 不足以报销"+sqbxje;
            }
        }
        return "";
    }
}
